import React from 'react';
import { InfoCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Select, Modal, Row, DatePicker, Input, Col, Checkbox } from 'antd';
import moment from 'moment';
import styles from '@/utils/utils.less';

const { confirm } = Modal;
const { TextArea } = Input;
const { MonthPicker } = DatePicker;
const { Option } = Select;
const FormItem = Form.Item;
class EmpUpdateModle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      endDayMonth: '',
      endDateYM: '',
      insuranceGroupFlag: true, // 业务开始日期按险种
      injSecFlag: false, // 判断是选择了执行账户之后，还是默认渲染
    };
  }

  getEndDay = day => {
    if (!day) return;
    const str = moment(day, 'YYYY-MM').format();
    const arr = str.split('-');
    const newDate = new Date(arr[0], arr[1], 1);
    const endDate = new Date(newDate.getTime() - 1000 * 60 * 60 * 24).getDate();
    this.setState({
      endDayMonth: `YYYY-MM-${endDate}`,
      endDateYM: (arr[0] + arr[1] + endDate).concat(''),
    });
  };

  // 对提交数据进行处理

  handleSubmitData = (values, addEmp) => {
    const { insData, dictData, social } = this.props;
    const { endDateYM } = this.state;
    let isDelareId = false;
    let isAddType = false;
    let isInjSer = false;
    let injSerAccoChange = false;
    const temp = values;
    // 下拉列表中是否已删除返回值(执行账户)
    if (addEmp === 1 && social === 2) {
      isDelareId =
        dictData.addDetInfoList[0].suppAccuAccos &&
        dictData.addDetInfoList[0].suppAccuAccos.some(
          item => item.accuAccoId === temp.declareAccuId
        );
    }
    if (addEmp === 1 && social === 1) {
      isDelareId =
        dictData.addDetInfoList[0].suppInsAccos &&
        dictData.addDetInfoList[0].suppInsAccos.some(item => item.insAccoId === temp.declareAccuId);
    }
    // 下拉列表中是否已删除返回值(参保类型)
    isAddType =
      dictData && dictData.addTypes.some(item => Number(item.itemCode) === Number(temp.addType));
    isInjSer =
      insData.injSecAccolist &&
      insData.injSecAccolist.some(item => String(item.injSecAccoId) === String(temp.injSerAccoId));
    injSerAccoChange =
      insData.injSecAccolist &&
      insData.injSecAccolist.some(item => String(item.insAccoId) === String(temp.insAccoId));
    if (temp.insMergAddList) {
      temp.insMergAddList = temp.insMergAddList.map((item, i) => ({
        addDetId: insData.insMergAddList[i].addDetId,
        ass: insData.insMergAddList[i].ass,
        beginDateYM: moment(item.beginDateYM).format('YYYYMMDD'),
      }));
    }
    temp.insMergFlag = insData.insMergFlag;
    const submitData = { ...temp, endDateYM };
    if (!isDelareId) submitData.declareAccuId = insData.declareAccuId || insData.declareAccoId;
    if (!isAddType) submitData.addType = insData.addType;
    if (!isInjSer && injSerAccoChange) submitData.injSerAccoId = insData.injSerAccoId;
    return submitData;
  };

  // 提交数据
  submitUpdateData = () => {
    const { form, submitUpdateData, addEmp, insData } = this.props;
    const { insuranceGroupFlag } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        const temp = values;
        if (
          insuranceGroupFlag &&
          Number(insData.insMergFlag) === 1 &&
          temp.beginDateYM &&
          Number(insData.mkupPayFlag) !== 1
        )
          delete temp.beginDateYM;
        if (!insuranceGroupFlag && temp.insMergAddList) delete temp.insMergAddList;
        // 减员
        this.setState({ insuranceGroupFlag: true });
        if (addEmp === 2) {
          confirm({
            title: '请将业务结束日期与相关客服人员确认后修改',
            okText: '已确认',
            cancelText: '未确认',
            icon: <InfoCircleOutlined />,
            onOk: () => {
              submitUpdateData(this.handleSubmitData(temp, addEmp));
              this.setState({ injSecFlag: false });
            },
            onCancel() {},
          });
        } else {
          submitUpdateData(this.handleSubmitData(temp, addEmp));
          this.setState({ injSecFlag: false });
        }

        // let isDelareId = false;
        // let isAddType = false;
        // let isInjSer = false;
        // // 下拉列表中是否已删除返回值(执行账户)
        // if (addEmp === 1 && social === 2) {
        //   isDelareId =
        //     dictData.addDetInfoList[0].suppAccuAccos &&
        //     dictData.addDetInfoList[0].suppAccuAccos.some(
        //       item => item.accuAccoId === values.declareAccuId
        //     );
        // }
        // if (addEmp === 1 && social === 1) {
        //   isDelareId =
        //     dictData.addDetInfoList[0].suppInsAccos &&
        //     dictData.addDetInfoList[0].suppInsAccos.some(
        //       item => item.insAccoId === values.declareAccuId
        //     );
        // }
        // // 下拉列表中是否已删除返回值(参保类型)
        // isAddType =
        //   dictData &&
        //   dictData.addTypes.some(item => Number(item.itemCode) === Number(values.addType));
        // isInjSer =
        //   insData.injSecAccolist &&
        //   insData.injSecAccolist.some(
        //     item => String(item.injSecAccoId) === String(values.injSerAccoId)
        //   );
        // const submitData = { ...values, endDateYM };
        // if (!isDelareId) submitData.declareAccuId = insData.declareAccuId || insData.declareAccoId;
        // if (!isAddType) submitData.addType = insData.addType;
        // if (!isInjSer) submitData.injSerAccoId = insData.injSerAccoId;
        // submitUpdateData(submitData);
      }
    });
  };

  disabledBeginTime = current => {
    const { insData, social, addEmp } = this.props;
    // 社保增员日期修改年月不限制
    if (social === 1 && addEmp === 1) {
      return false;
    }
    if (insData.endDate) {
      return (
        current < moment(insData.endDate, 'YYYY-MM').endOf('day') || current > moment().endOf('day')
      );
    }
    return current < moment(insData.beginDateYM, 'YYYY-MM').endOf('day');
  };

  disabledEndTime = current => {
    const { insData } = this.props;
    // 上月可选
    if (!insData.lastMthOptalFlag) {
      // 应该减一个月
      return current > moment(insData.endDateYM, 'YYYY-MM').endOf('day');
    }
    // 上月不可选
    return (
      current > moment(moment(insData.endDateYM, 'YYYY-MM').subtract(0, 'months')).endOf('day')
    );
  };

  // 执行账户是否已删除
  renderDeclareId = () => {
    const { addEmp, dictData, insData, social } = this.props;
    let isDelareId = false;
    if (addEmp === 1 && social === 2) {
      isDelareId =
        dictData.addDetInfoList[0].suppAccuAccos &&
        dictData.addDetInfoList[0].suppAccuAccos.some(
          item => item.accuAccoId === insData.declareAccuId
        );
    }
    if (addEmp === 1 && social === 1) {
      isDelareId =
        dictData.addDetInfoList[0].suppInsAccos &&
        dictData.addDetInfoList[0].suppInsAccos.some(
          item => item.insAccoId === insData.declareAccoId
        );
    }
    return isDelareId;
  };

  // 参保类型是否已删除
  renderAddType = () => {
    const { dictData, insData } = this.props;
    let isAddType = false;
    isAddType = dictData.addTypes.some(item => Number(item.itemCode) === Number(insData.addType));
    return isAddType;
  };

  updateGetInjList = insAccoId => {
    const {
      form,
      getInjList, // 选择执行账户事件
    } = this.props;
    this.setState({
      injSecFlag: true,
    });
    form.setFieldsValue({ injSerAccoId: '' });
    getInjList(insAccoId);
  };

  checkInsurance = val => {
    this.setState({ insuranceGroupFlag: val.target.checked });
  };

  close = () => {
    const { visUpdateModle } = this.props;
    this.setState({ insuranceGroupFlag: true, injSecFlag: false });
    visUpdateModle(false);
  };

  render() {
    //
    const {
      form: { getFieldDecorator },
      addEmp,
      visUpdate,
      dictData,
      insData,
      social,
      requiredFlag, // 是否显示二级户
      injSecAccoDatalist,
      persion,
    } = this.props;
    const { injSecAccolist } = insData;
    const { injSecFlag, insuranceGroupFlag } = this.state;
    const isInjSer =
      insData.injSecAccolist &&
      insData.injSecAccolist.some(
        item => String(item.injSecAccoId) === String(insData.injSerAccoId)
      );
    const { endDayMonth } = this.state;
    const insuranceGroup = insuranceGroupFlag ? styles.show : styles.hide;
    const checkFlag =
      Number(insData.insMergFlag) === 1 && Number(insData.mkupPayFlag) !== 1
        ? styles.show
        : styles.hide;
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 6,
        },
      },
      wrapperCol: {
        xs: {
          span: 17,
        },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 18,
          offset: 6,
        },
        md: {
          span: 18,
          offset: 6,
        },
      },
    };
    const changeMonthEnd = (date, dateString) => {
      const arr = dateString.split('-');
      this.getEndDay(moment(Number(arr[0] + arr[1]), 'YYYY-MM'));
    };
    // 执行账户选项
    const declare = () => {
      if (addEmp === 1 && social === 2) {
        return (
          <Select style={{ width: '100%' }}>
            {dictData.addDetInfoList[0].suppAccuAccos &&
              dictData.addDetInfoList[0].suppAccuAccos.map(options => (
                <Option key={options.accuAccoId}>{options.accoName}</Option>
              ))}
          </Select>
        );
      }
      if (addEmp === 1 && social === 1) {
        return (
          <Select
            onChange={insAccoId => this.updateGetInjList(insAccoId)}
            style={{ width: '100%' }}
          >
            {dictData.addDetInfoList[0].suppInsAccos &&
              dictData.addDetInfoList[0].suppInsAccos.map(options => (
                <Option key={options.insAccoId}>{options.accoName}</Option>
              ))}
          </Select>
        );
      }
      return null;
    };
    // 二级户
    const renderInjList = () => {
      if (injSecFlag && requiredFlag) {
        return (
          <Row>
            <FormItem {...formItemLayout} label={<span>工伤二级户</span>}>
              {getFieldDecorator('injSerAccoId', {
                rules: [
                  {
                    required: requiredFlag,
                    message: '二级户名称',
                  },
                ],
              })(
                <Select style={{ width: '100%' }}>
                  {injSecAccoDatalist.map(options => (
                    <Option key={options.injSecAccoId} value={options.injSecAccoId}>
                      {options.injSecAccoName}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Row>
        );
      }

      return (
        <Row>
          <FormItem {...formItemLayout} label={<span>工伤二级户</span>}>
            {getFieldDecorator('injSerAccoId', {
              rules: [
                {
                  required: requiredFlag,
                  message: '二级户名称',
                },
              ],
              initialValue: isInjSer ? insData.injSerAccoId.toString() : insData.injSerAccoName,
            })(
              <Select style={{ width: '100%' }}>
                {injSecAccolist.map(options => (
                  <Option key={options.injSecAccoId} value={options.injSecAccoId}>
                    {options.injSecAccoName}
                  </Option>
                ))}
              </Select>
            )}
          </FormItem>
        </Row>
      );
    };

    return (
      <Modal
        title={social === 2 ? '公积金信息' : '社保信息'}
        visible={visUpdate}
        okText="确定"
        cancelText="取消"
        onOk={this.submitUpdateData}
        onCancel={this.close}
        destroyOnClose
      >
        {addEmp === 1 && Number(insData.payWay) !== 1 ? (
          <Row>
            <FormItem {...formItemLayout} label={<span>执行账户</span>}>
              {getFieldDecorator('declareAccuId', {
                rules: [
                  {
                    required: true,
                    message: '请选择执行账户',
                  },
                ],

                initialValue: this.renderDeclareId()
                  ? insData.declareAccuId || insData.declareAccoId
                  : insData.declareAccuName || insData.declareAccoName,
              })(declare())}
            </FormItem>
          </Row>
        ) : null}

        {addEmp === 1 && social === 1 && requiredFlag ? renderInjList() : null}

        {addEmp === 1 ? (
          <Row>
            <FormItem {...formItemLayout} label={<span>参保类型</span>}>
              {getFieldDecorator('addType', {
                rules: [
                  {
                    required: false,
                    message: '请选择参保类型',
                  },
                ],
                initialValue: this.renderAddType()
                  ? insData.addType.toString()
                  : insData.addTypeName,
              })(
                <Select style={{ width: '100%' }}>
                  {dictData.addTypes.map(options => (
                    <Option key={options.itemCode}>{options.itemName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Row>
        ) : null}
        {/* 缴费人员类别（若当前地区不区分缴费人员类别将不显示此字段） */}
        {addEmp === 1 && insData.isJoinIdeId && Number(insData.isJoinIdeId) === 1 && (
          <Row>
            <FormItem {...formItemLayout} label={<span>缴费人员类别</span>}>
              {getFieldDecorator('joinIdeId', {
                rules: [
                  {
                    required: true,
                    message: '请选择缴费人员类别',
                  },
                ],
                initialValue: insData.joinIdeId ? insData.joinIdeId : undefined,
              })(
                <Select style={{ width: '100%' }}>
                  {dictData.joinDtos.map(options => (
                    <Option key={options.ideId}>{options.ideName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Row>
        )}

        {addEmp === 1 ? (
          <Row>
            <FormItem {...formItemLayout} label="业务开始日期">
              {getFieldDecorator('beginDateYM', {
                rules: [
                  {
                    required: true,
                    message: '请选择业务开始日期',
                  },
                ],
                initialValue: insData.beginDateYM
                  ? moment(insData.beginDateYM, 'YYYY-MM-01')
                  : undefined,
              })(
                <MonthPicker
                  disabledDate={this.disabledBeginTime}
                  format="YYYY-MM-01"
                  placeholder="请选择"
                  style={{ width: '100%' }}
                  disabled={insuranceGroupFlag && Number(insData.insMergFlag) === 1}
                />
              )}
            </FormItem>
            <div className={checkFlag} style={{ width: '100%' }}>
              <FormItem {...tailFormItemLayout}>
                {getFieldDecorator('agreement', {
                  valuePropName: 'checked',
                  initialValue: true,
                })(<Checkbox onChange={e => this.checkInsurance(e)}>按险种</Checkbox>)}
              </FormItem>
              <Row className={insuranceGroup}>
                {insData &&
                  insData.insMergAddList &&
                  insData.insMergAddList.map((item, i) => (
                    <FormItem {...formItemLayout} label={item.assName} key={item.ass}>
                      {getFieldDecorator(`insMergAddList[${i}][beginDateYM]`, {
                        rules: [
                          {
                            required: true,
                            message: '请选择业务开始日期',
                          },
                        ],
                        initialValue: item.beginDateYM
                          ? moment(item.beginDateYM, 'YYYY-MM-01')
                          : undefined,
                      })(
                        <MonthPicker
                          disabledDate={this.disabledBeginTime}
                          format="YYYY-MM-01"
                          placeholder="请选择"
                          style={{ width: '100%' }}
                        />
                      )}
                    </FormItem>
                  ))}
              </Row>
            </div>
            <Col span={17} offset={6} style={{ marginTop: '-26px', marginBottom: '16px' }}>
              {insData.mkupPayFlag === 1 ? (
                <span style={{ fontSize: 14, color: '#999' }}>
                  注：当前员工险种已添加个人补缴，如需修改请联系员工服务人员将个人补缴信息删除。
                </span>
              ) : null}
            </Col>
          </Row>
        ) : (
          <Row>
            <Row>
              <FormItem {...formItemLayout} label="业务开始日期">
                {getFieldDecorator('beginDateYM', {
                  rules: [
                    {
                      required: false,
                      message: '请选择业务开始日期',
                    },
                  ],
                  initialValue: insData.beginDateYM
                    ? moment(insData.beginDateYM, 'YYYY-MM-01')
                    : undefined,
                })(
                  <MonthPicker
                    disabled
                    placeholder="请选择"
                    style={{ width: '100%' }}
                    format="YYYY-MM-01"
                  />
                )}
              </FormItem>
            </Row>
            <Row>
              <FormItem {...formItemLayout} label="业务结束日期">
                {getFieldDecorator('endDateYM', {
                  rules: [
                    {
                      required: true,
                      message: '请选择业务结束日期',
                    },
                  ],
                  initialValue: insData.endDateYM
                    ? moment(insData.endDateYM, 'YYYY-MM')
                    : undefined,
                })(
                  <MonthPicker
                    disabledDate={this.disabledEndTime}
                    onChange={(date, dateString) => {
                      changeMonthEnd(date, dateString);
                    }}
                    format={endDayMonth || this.getEndDay(insData.endDateYM)}
                    placeholder="请选择"
                    style={{ width: '100%' }}
                  />
                )}
              </FormItem>
              {persion.declStatus === '申报中' ? null : (
                <Col span={17} offset={6} style={{ marginTop: '-26px', marginBottom: '16px' }}>
                  <span style={{ fontSize: 14, color: '#999' }}>
                    注：修改业务结束日期小于业务开始日期，系统将自动转成取消增减员任务。
                  </span>
                </Col>
              )}
            </Row>
          </Row>
        )}
        <Row style={{ marginTop: -10 }}>
          <FormItem {...formItemLayout} label={<span>备注</span>}>
            {getFieldDecorator('cause', {
              rules: [
                {
                  required: true,
                  message: '请输入备注',
                },
              ],
            })(<TextArea placeholder="请输入备注" autoSize={{ minRows: 3, maxRows: 6 }} />)}
          </FormItem>
        </Row>
      </Modal>
    );
  }
}
export default Form.create()(EmpUpdateModle);
